import { List } from 'react-vant';
import './Collection.css';
import { useState } from 'react';
import collectionApi from '@/apis/collectionApi';
import GoodCard from '@/components/GoodCard';
import { promptResult } from '@/utils/common';

const limit = 10;

const Collection: React.FC = () => {
  const [collections, setCollections] = useState<ResponseHistoryDto[]>([]);
  const [loading, setLoading] = useState(true);
  const [finished, setFinished] = useState(false);
  const [page, setPage] = useState(1);

  const loadMore = async () => {
    const res = await collectionApi.getCollectionPagination(page, limit);
    if (res.status >= 0) {
      setCollections(res.data.data);
      setPage((prev) => prev + 1);
      if (res.data.data.length < limit) {
        setFinished(true);
      }
    }
  };

  const handleDelete = async (id: number) => {
    promptResult(
      collectionApi.cancelCollection(id),
      () => {},
      () => {
        setCollections(collections.filter((d) => d.id != id));
      }
    );
  };

  return (
    <>
      <List onLoad={loadMore} finished={finished} finishedText="没有更多了">
        {collections.map((d) => {
          return <GoodCard key={d.id} good={d.good} onDelete={() => handleDelete(d.id)} />;
        })}
      </List>
    </>
  );
};

export default Collection;
